<?php

namespace App\Http\Controllers\Admin;

use App\Handler\ImageHandler;
use App\Http\Requests\Admin\AdminRequest;
use App\Http\Requests\Admin\AdminUpdateRequest;
use App\Models\Admin;
use App\Models\AdminLog;
use App\Models\AdminRole;
use App\Models\Role;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{
	use ImageHandler;
	/**
	 * 显示管理员列表
	 * User: ihome
	 */
	public function index(Role $roleModel)
    {
    	//非系统管理员看不到系统管理员账号
    	if(auth('admin')->id() != 1){
			$where = [
    			['admin.id','>','1'],
			];
    	}else{
    		$where = [];
		}

		$adminList = Admin::query()
					->select('admin.id','thumb','username','status','admin.created_at','nickname',
						\DB::raw('GROUP_CONCAT(`my_role`.role_name) as role_name')
					)
					->leftJoin('admin_role',function ($lefJoin){
						$lefJoin->on('admin_role.admin_id','=','admin.id')
							->whereNull('admin_role.deleted_at');
					})
					->leftJoin('role',function ($leftJoin){
						$leftJoin->on("admin_role.role_id",'=','role.id')
						->whereNull('role.deleted_at');
					})
					->orderBy('created_at','desc')
					->groupBy('admin.id')
					->where($where)
					->paginate(10);

		return view('admin.admin.index',compact('adminList'));
    }

	/**
	 * 添加管理员
	 * User: ihome
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function create()
    {
    	//取出所有的角色列表
		$roles = Role::query()->select(['role_name','id'])->get();

		return view('admin.admin.create',compact('roles'));
    }

	/**
	 * 添加管理员动作
	 * User: ihome
	 * @param AdminRequest $request
	 * @param Admin $adminModel
	 * @return \Illuminate\Http\RedirectResponse
	 */
	public function store(AdminRequest $request,Admin $adminModel)
    {
		if(\request()->method() == 'POST'){
			$insertData = $request->except(['_token','thumb','role_id']);

			//判断有没有图片上传
			if($request->hasFile('thumb')){
				$imgUpload = $this->imageUploader('uploads/admin','thumb');

				if($imgUpload['status'] == '200'){
					$insertData['thumb'] = $imgUpload['path'];
				}else{
					return back()->with('danger',$imgUpload['msg']);
				}
			}

			//没有填年龄
			if(!$insertData['age']){
				$insertData['age'] = 0;
			}

			$insertData['password'] = bcrypt($insertData['password']);

			$adminModel->fill($insertData);
			$adminModel->save();

			//角色的关联
			$adminModel->role()->attach($request->input('role_id'));

			return redirect()->route('admin.admin.index')->with('success','添加成功');
		}
    }

	/**
	 * 修改管理员显示
	 * User: ihome
	 * @param $id
	 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
	 */
	public function edit($id)
    {
		$adminInfo = Admin::with(['role'])->findOrFail($id)->toArray();

		$role_ids = [];
		foreach ($adminInfo['role'] as $k => $v) {
		    $role_ids[] = $v['pivot']['role_id'];
		}

		//取出所有的角色列表
		$roles = Role::query()->select(['role_name','id'])->get();

		return view('admin.admin.edit',compact('adminInfo','role_ids','roles'));
    }

	/**
	 * 修改管理员动作
	 * User: ihome
	 * @param AdminUpdateRequest $request
	 * @param $id
	 * @return \Illuminate\Http\RedirectResponse
	 */
	public function update(AdminUpdateRequest $request,$id)
    {
		if(\request()->method() == 'POST'){

			$admin = Admin::findOrFail($id);

			if($id != 1){
				$adminData = $request->except(['_token','thumb','username','role_id']);
			}else{
				//超级系统管理员只能接收这些
				$adminData = $request->only(['username','age','password','nickname']);
			}

			//判断图片
			if($request->hasFile('thumb')){
				$uploadImg = $this->imageUploader('uploads/admin','thumb');
				if($uploadImg['status'] == 200){
					$adminData['thumb'] = $uploadImg['path'];

					//删除原图
					@unlink( public_path() . '/' . $admin->thumb);
				}else{
					return back()->with('info',$uploadImg['msg']);
				}
			}

			if($adminData['password']){
			    $adminData['password'] = bcrypt($adminData['password']);
			}else{
				unset($adminData['password']);
			}

			//没有填年龄
			if(!$adminData['age']){
			    $adminData['age'] = 0;
			}

			$admin->fill($adminData);
			$admin->where('id',$id)->update($adminData);

			//角色的关联
			$admin->role()->sync($request->input('role_id'));

			return redirect()->route('admin.admin.index')->with('success','更新成功');
		}
    }

	/**
	 * 软删除管理员
	 * User: ihome
	 * @param $id
	 * @return \Illuminate\Http\RedirectResponse
	 */
	public function destroy($id)
    {
		$admin = Admin::findOrFail($id);

		if($id != 1){
			$admin->delete();
			return redirect()->route('admin.admin.index')->with('success','删除成功');
		}else{
			return redirect()->route('admin.admin.index')->with('danger','系统管理员不可删除');
		}
    }

	/**
	 * 管理员日志
	 * User: Clannad ~ ☆
	 * DataTime：2019/11/24 0024 14:56
	 */
	public function login_log()
    {
		$logList = AdminLog::query()
				->select('admin.nickname','admin.username','admin_log.login_time','admin_log.login_ip','admin_log.id')
				->leftJoin('admin','admin.id','=','admin_log.admin_id')
				->orderBy('admin_log.id','desc')
				->paginate(10);

		return view('admin.admin.login_log',compact('logList'));
    }
}
